
import { BATTLE_ASSET } from "const/assets";
import SenseManager, { sense } from "utils/SenseManager";
import Map from "battle/components/Map";
import socket from "ctrl/socket";
import GamePanel from "battle/components/GamePanel";
import RoleManger from "battle/components/RoleManger";

const { Event } = Laya;

let enterData;

@sense("/battle")
export default class BattleSense extends Laya.Sprite {

    getAsset() {
        return BATTLE_ASSET;
    }

    willMount() {
        return new Promise((reslove, reject)=> {
            socket.once("enter", data=> {
                enterData = data;
                let roleTypes = [];
                reslove();
            });
            socket.send("enter");
        });
    }

    constructor() {
        super();
        this.init();
    }

    init() {
        this.resizable(()=> {
            this.height = Laya.stage.height;
            this.width = Laya.stage.width;
        });

        let mapview = this.mapview = Map.getInstance();
        this.addChild(mapview);

        let operatorView = this.operatorView = GamePanel.getInstance();
        this.addChild(operatorView);
    }

    didMount() {
        if (!enterData) return;
        enterData.player.forEach(data=> {
            data.roomNo = enterData.roomNo;
            let role = RoleManger.createRole(data);
            role.putInMap();
        });
        RoleManger.roomNo = enterData.roomNo;

        socket.once("start", (data)=> {
            console.log("游戏开始");
        });
        let startime = Date.now();
        socket.send("start", { timestamp: startime });
        

        socket.on("sync", (data)=> {
            RoleManger.getRoles().forEach(role=> {
                let roleData = data.role.find(v=> v.uid==role.uid);
                if (roleData) {
                    role.syncData = roleData;
                    if (role.isMyRole) {
                        role.checkFromServer();
                    } else {
                        role.syncFromServer();
                    }
                }
            });
        });

    }

    willUnMount() {
        
    }

}